package com.wang.dao.impl;

import com.wang.dao.BookDao;
import com.wang.entry.Book;
import com.wang.util.DBHelper;

import java.util.ArrayList;

public class BookDaoImpl implements BookDao {

    DBHelper db = new DBHelper();

    @Override
    public ArrayList<Book> selectAll() {
        String sql = "select * from book";
        return db.query(sql, Book.class);
    }

    @Override
    public ArrayList<Book> selectQuery(Book book) {
        StringBuilder sql =new StringBuilder("select * from book where 1=1 ");
        if(book.getBookName()!=null){
            sql.append( "and BOOKNAME like ?");
            return db.query(sql.toString(), Book.class,"%"+book.getBookName()+"%");
        }else if(book.getBookAuthor()!=null){
            sql.append( "and BOOKAUTHOR like ?");
            return db.query(sql.toString(), Book.class,"%"+book.getBookAuthor()+"%");
        }else if(book.getBookPublish()!=null){
            sql.append( "and BOOKPUBLISH like ?");
            return db.query(sql.toString(), Book.class,"%"+book.getBookPublish()+"%");
        }else{
            return db.query(sql.toString(), Book.class);
        }
    }

    @Override
    public boolean insertBook(Book book) {
        String sql="insert into book (BOOKNAME,BOOKAUTHOR,BOOKPUBLISH,BOOKPAGE,BOOKPRICE,CREATEDATE) " +
                "values(?,?,?,?,?,?)";
        return db.updateTable(sql,book.getBookName(),book.getBookAuthor(),book.getBookPublish(),book.getBookPage(),book.getBookPrice(),book.getCreateDate())==0?false:true;
    }

    @Override
    public boolean deleteBookById(int id) {
        String sql="delete from book where bookid = ?";
        return db.updateTable(sql,id)==0?false:true;

    }

    @Override
    public boolean updateBook(Book book) {
        StringBuilder sb = new StringBuilder("update book set BOOKNAME=? ,BOOKAUTHOR=? ,BOOKPUBLISH=? ,BOOKPAGE=? ,BOOKPRICE=? ,CREATEDATE= ? where BOOKID=?");
        Object[] objs = {book.getBookName(), book.getBookAuthor(), book.getBookPublish(), book.getBookPage(), book.getBookPrice(), book.getCreateDate(), book.getBookId()};
        return db.updateTable(sb.toString(), objs) > 0 ? true : false;
    }

    @Override
    public Book selectById(int id) {
        String sql = "select * from book where id=?";
        return (Book)db.query(sql,Book.class,id).get(0);
    }
}
